package com.leyikao.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONObject;


/**
 * 接口工具类
 * @author Administrator
 *
 */
public class HttpRequest {
    
	private static final String CHARSET = "UTF-8";
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
	
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {

            URL realUrl = new URL(url);
            // 打开和URL之间的连接 Accept-Encoding: gzip,deflate,sdch
            URLConnection connection = realUrl.openConnection(); 
            connection.setConnectTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),CHARSET));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true); 
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),CHARSET));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
    
    public String post(String params){
    	PropertiesUtil propertiesUtil= new PropertiesUtil(this.getClass().getResource("/").getPath()+"/com/leyikao/config/config.properties");
		String url = propertiesUtil.getProperty("ent_url");
		String token = propertiesUtil.getProperty("ent_token");
		String name = propertiesUtil.getProperty("ent_name");
		String param = name+"={\"token\":\""+token+"\",\"type\":"+params+"}";
		return HttpRequest.sendPost(url, param);
    }
    
    public static void  main(String[] str){
    	HttpRequest hr = new HttpRequest();
    	int page = 1; 
    	String education_type = "-1";
    	String salary_min = "";
    	String salary_max = "";
    	String major_id = "0";
    	String a = "post_json={\"token\":\"0a20ece95e098dd38621410f5a3f8dda\",\"type\":\"ent_resume_search_list\",\"ent_resume_search_list\",\"page\":\""+page+"\",\"certificate_type\":\""+education_type+"\",\"salary_min\":\""+salary_min+"\",\"salary_max\":\""+salary_max+"\",\"major_id\":\""+major_id+"\"}";
    	String s = hr.sendPost("http://42.62.92.59/interface_ent/",a);
    	JSONObject jsonObject = JSONObject.fromObject(s);
    	Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
    	System.out.println(mapJson);
    }
}